package edu.uoc.tdp.client.estudiants;

import edu.uoc.tdp.beans.conexio.Estudiant;
import edu.uoc.tdp.beans.proves.Prova;
import edu.uoc.tdp.common.EOlympicsException;
import edu.uoc.tdp.common.RemotEstudiantsInterface;
import edu.uoc.tdp.common.TDSLanguageUtils;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;

/**
 * Pantalla per a validar la inscripció
 * @author Jordi
 */
public class PantallaValidacio extends javax.swing.JFrame {
    private RemotEstudiantsInterface remot;
    private Estudiant estudiant;
    private Prova prova;
    private int preguntesinscrit;
    
    /**
     * Constructor amb dos paràmetres   
     * @param pEstudiant           Identificador de l'estudiant actual
     * @param pRemot               Remot que ens permet connectar amb el servidor
     */
    public PantallaValidacio(Prova pProva,Estudiant pEstudiant,RemotEstudiantsInterface pRemot) {
        estudiant = pEstudiant;
        remot = pRemot;
        prova = pProva;
        preguntesinscrit = 0;
        
        initComponents();
        carregainicial();
        
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {            
            public void windowClosing(java.awt.event.WindowEvent evt) {
                tancarFinestra(evt);
            }
        });
    }


    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jPasswordField1 = new javax.swing.JPasswordField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "FORMULARI D'INSCRIPCIO", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 14), new java.awt.Color(0, 0, 255))); // NOI18N

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel1.setForeground(new java.awt.Color(0, 0, 255));
        jLabel1.setText("Inscrit en n proves");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable1.setEnabled(false);
        jScrollPane1.setViewportView(jTable1);

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel2.setForeground(new java.awt.Color(0, 0, 255));
        jLabel2.setText("Alta en prova:");

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel3.setForeground(new java.awt.Color(0, 0, 255));
        jLabel3.setText("Contrasenya:");

        jPasswordField1.setColumns(10);
        jPasswordField1.setToolTipText("");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(34, 34, 34)
                        .addComponent(jLabel1))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 412, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(40, 40, 40)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addGap(43, 43, 43)
                                .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jLabel2)
                .addGap(35, 35, 35)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(71, Short.MAX_VALUE))
        );

        jButton1.setText("Acceptar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Tornar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addGap(18, 18, 18)
                        .addComponent(jButton2)
                        .addGap(31, 31, 31))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap(19, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
     /**
     * Inscriu l'estudiant a la prova si la contrassenya entrada és correcte i no esta inscrit a més de 5 proves
     * @param evt               disparador
     */ 
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
       try {
            
            if (preguntesinscrit < 5) {
                int n = JOptionPane.showConfirmDialog(
                        null,
                        TDSLanguageUtils.getMessage("estudiants.pantalla.validacio.pregunta.inscriure.miss") + prova.getDescripcio() + "?",
                        TDSLanguageUtils.getMessage("estudiants.pantalla.validacio.pregunta.inscriure.title"),
                        JOptionPane.YES_NO_OPTION); 
               
                if (n == 0 && jPasswordField1.getText().equals(estudiant.getPwd().toString())){    
                    boolean Inscriure = remot.Inscriure(prova.getIdProva(), estudiant.getIdIntern());
                    if(Inscriure){   
                        JOptionPane.showMessageDialog(
                        null, TDSLanguageUtils.getMessage("estudiants.pantalla.validacio.inscripcio.miss"),
                        TDSLanguageUtils.getMessage("estudiants.pantalla.validacio.inscripcio.title"),
                        JOptionPane.INFORMATION_MESSAGE);
                    }
                    dispose(); 
                
                } else if(n == 0 && !jPasswordField1.getText().equals(estudiant.getPwd().toString())){
                    JOptionPane.showMessageDialog(
                    null, TDSLanguageUtils.getMessage("estudiants.pantalla.validacio.error.password.miss") + estudiant.getIdUsuari(),
                    TDSLanguageUtils.getMessage("estudiants.pantalla.validacio.error.password.title"), JOptionPane.ERROR_MESSAGE);
                  }
            
            } else {
               JOptionPane.showMessageDialog 
                    (null, TDSLanguageUtils.getMessage("estudiants.pantalla.validacio.error.numproves.miss"),
                     TDSLanguageUtils.getMessage("estudiants.pantalla.validacio.error.numproves.title"), JOptionPane.ERROR_MESSAGE);
              }
           
        } catch (RemoteException ex) {
            JOptionPane.showMessageDialog 
             (null,TDSLanguageUtils.getMessage("estudiants.common.error.conexio.miss"),
              TDSLanguageUtils.getMessage("estudiants.common.error.literalerror"), JOptionPane.ERROR_MESSAGE);
            
        } catch (EOlympicsException ex) {
            JOptionPane.showMessageDialog 
             (null, ex.getMessage(), TDSLanguageUtils.getMessage("estudiants.common.error.literalerror"), JOptionPane.ERROR_MESSAGE);
        }
}//GEN-LAST:event_jButton1ActionPerformed

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
       tancarFinestraboto(evt);
}//GEN-LAST:event_jButton2ActionPerformed
     /**
     * Fa la primera carrega de la pantalla. Posant el valor a els elements de texte i fent la carrega
     * de les proves inscrites
     */    
private void carregainicial(){
        try {
            TDSLanguageUtils.setDefaultLanguage("edu/uoc/tdp/i18n/messages");
            this.setTitle(TDSLanguageUtils.getMessage("estudiants.pantalla.validacio.nom"));
            jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, TDSLanguageUtils.getMessage("estudiants.pantalla.validacio.title"),
                              javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION,
                              new java.awt.Font("Tahoma", 0, 14), new java.awt.Color(0, 0, 255)));

            jLabel2.setText(TDSLanguageUtils.getMessage("estudiants.pantalla.validacio.descripcioprova") + prova.getDescripcio());
            jLabel3.setText(TDSLanguageUtils.getMessage("estudiants.pantalla.validacio.password") );
            jButton1.setText(TDSLanguageUtils.getMessage("estudiants.pantalla.validacio.Button.OK"));
            jButton2.setText(TDSLanguageUtils.getMessage("estudiants.pantalla.validacio.Button.tornar"));
            
            Prova table_prova = new Prova();

            List<Prova> entrada = new ArrayList<Prova>();
            entrada = remot.ProvesInscritesTotals(estudiant.getIdIntern());
            
            DefaultTableModel modelo = new DefaultTableModel()
            {
                @Override
                public boolean isCellEditable(int rowIndex, int columnIndex) {
                return false;
                }
            };
            
            modelo.addColumn(TDSLanguageUtils.getMessage("estudiants.pantalla.validacio.col1"));
            modelo.addColumn(TDSLanguageUtils.getMessage("estudiants.pantalla.validacio.col2"));
            modelo.addColumn(TDSLanguageUtils.getMessage("estudiants.pantalla.validacio.col3"));
            int i;
            
            preguntesinscrit = entrada.size();
            
            for (i = 0;i<preguntesinscrit;i++) { 
 
                table_prova = entrada.get(i);
                Object[] fila = new Object[3];
                fila[0] = table_prova.getDescripcio(); 
                if(table_prova.getRondaEliminatoria() == null){
                    fila[1] = TDSLanguageUtils.getMessage("estudiants.common.final");
                    fila[2] = table_prova.getRondaFinal().getNombrePreguntes();
                } else {
                    fila[1] = TDSLanguageUtils.getMessage("estudiants.common.eliminatoria");
                    fila[2] = table_prova.getRondaEliminatoria().getNombrePreguntes();
                  }       
                modelo.addRow(fila); 
            } 
            this.jTable1.setModel(modelo); 
            
            String missatge = TDSLanguageUtils.getMessage("estudiants.pantalla.validacio.missatge1") 
                              + i + " " 
                              + TDSLanguageUtils.getMessage("estudiants.pantalla.validacio.missatge2");
            jLabel1.setText(missatge);
                                    
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    } 
        
     /**
     * Tancament de la finestra des de d'un windowevent
     * @param evt               disparador
     */
    private void tancarFinestra(java.awt.event.WindowEvent evt) {
        dispose();
        System.exit(0);
    }
        /**
     * Tancament de la finestra des des del boto tancar
     * @param evt               disparador
     */  
    private void tancarFinestraboto (java.awt.event.ActionEvent evt) {
        dispose();
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPasswordField jPasswordField1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables
}
